package m202406.d29;

import java.util.Arrays;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/29 15:15
 */
public class Q416 {

    public static void main(String[] args) {
        Q416 q416 = new Q416();
        q416.canPartition(new int[]{14, 9, 8, 4, 3, 2});
    }

    public boolean canPartition(int[] nums) {
        if (nums.length < 2) {
            return false;
        }
        int sum = 0;
        int max = 0;
        for (int num : nums) {
            sum = sum + num;
            max = Math.max(max, num);
        }
        if (sum % 2 != 0) {
            return false;
        }
        int target = sum / 2;
        if (max > target) {
            return false;
        } else if (max == target) {
            return true;
        }

        int n = nums.length;
        boolean[][] dp = new boolean[n][target + 1];
        //初始化dp[i][0]
        for (int i = 0; i < dp.length; i++) {
            dp[i][0] = true;
        }
        //初始化dp[0][nums[0]] = true;
        dp[0][nums[0]] = true;

        //递推 j>nums[i]  dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i]]
        for (int i = 1; i < n; i++) {
            for (int j = 1; j <= target; j++) {
                if (j >= nums[i]) {
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j-nums[i]];
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[n - 1][target];
    }

    //行不通
    public boolean canPartition1(int[] nums) {
        if (nums.length < 2) {
            return false;
        }
        int sum = 0;
        int max = 0;
        for (int num : nums) {
            sum = sum + num;
            max = Math.max(max, num);
        }
        if (sum % 2 != 0) {
            return false;
        }
        int target = sum / 2;
        if (max > target) {
            return false;
        } else if (max == target) {
            return true;
        }

        Arrays.sort(nums);
        int start = 0;
        int end = 0;
        int temp = 0;
        while (end < nums.length) {
            if (temp < target) {
                end++;
                temp = temp + nums[end - 1];
            } else if (temp > target) {
                temp = temp - nums[start];
                start++;
            } else {
                return true;
            }
        }
        return temp == target;
    }
}
